package tianwu.pic;

import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JFrame;
import java.awt.Canvas;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class UI {

	private JFrame frame;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UI window = new UI();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public UI() {
		initialize();
		new Network(2234,this).start();
		new NetworkServer(2235).start();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	Canvas canvas;
	Image image;
	synchronized public void drawNewImage(Image image){
		System.out.println("updata.");
		this.image = image;
		canvas.update(canvas.getGraphics());
	}
	private void initialize() {
		frame = new JFrame();
		frame.setResizable(false);
		frame.setBounds(100, 100, 767, 685);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		canvas = new Canvas(){
			private static final long serialVersionUID = 1L;
			public void paint(Graphics g){
				if(image!=null){
					g.drawImage(image, 10, 10,null);
				}
			}
		};
		frame.getContentPane().add(canvas, BorderLayout.CENTER);
		
		Button button = new Button("TakePicture");
		button.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				try {
					@SuppressWarnings("resource")
					Socket socket = new Socket("192.168.23.1",2235);
					DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
					dos.writeInt(1);
					dos.flush();
					dos.close();
				} catch (UnknownHostException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				
			}
		});
		frame.getContentPane().add(button, BorderLayout.EAST);
	}

}
